package com.andon.microcellsimulator.common.util;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Dialog;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.hardware.Camera;
import android.location.LocationListener;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.View;
import android.view.WindowManager;

import com.andon.microcellsimulator.activity.MainActivity;
import com.andon.microcellsimulator.common.base.ZnkApplication;
import com.andon.microcellsimulator.common.dialog.ZnkAlertDialog;
import com.andon.microcellsimulator.common.dialog.ZnkConfirmDialog;
import com.andon.microcellsimulator.common.dialog.ZnkConfirmWarningDialog;
import com.andon.microcellsimulator.common.dialog.ZnkProgressDialog;
import com.andon.microcellsimulator.http.Client;

public class ZnkActivityUtil {

    private static Activity activityContext;
    private static ZnkProgressDialog loadingDialog;
    private static Dialog tokenErrorDialog;

    private static LocationListener sLocationListener;

    public static Context getContext() {
        return activityContext;
    }

    public static void setContext(Activity context) {
        activityContext = context;
    }

    public static void showSimpleDialog(String message) {

        Dialog dialog = ZnkAlertDialog.createDialog(activityContext, message, null);

        dialog.show();
    }

    public static void showSimpleDialog(Context context, String message) {

        showSimpleDialog(context, message, null);

    }

    public static void showSimpleDialog(Context context, String message, ZnkAlertDialog.OnClickCallBack callBack) {

        Dialog dialog = ZnkAlertDialog.createDialog(context, message, callBack);

        dialog.show();
    }

    public static void showConfirmDialog(Context context, String message, ZnkConfirmDialog.OnClickCallBack confirmCallback, ZnkConfirmDialog.OnClickCallBack cancelCallback) {
        // 创建提示窗口
        Dialog dialog = ZnkConfirmDialog.createDialog(context, message, confirmCallback, cancelCallback);

        dialog.show();
    }

    public static void showConfirmWarningDialog(Context context, String message, ZnkConfirmWarningDialog.OnClickCallBack confirmCallback, ZnkConfirmWarningDialog.OnClickCallBack cancelCallback) {
        // 创建提示窗口
        Dialog dialog = ZnkConfirmWarningDialog.createDialog(context, message, confirmCallback, cancelCallback);

        dialog.show();
    }

    public static void startActivity(Context context, Class<? extends Activity> cls) {
        Intent intent = new Intent(context, cls);
        intent.putExtra("name", context.getClass().getSimpleName());
        context.startActivity(intent);
    }

    public static void finishActivity() {
        if (activityContext != null) {
//            if (activityContext instanceof BaseActivity) {
//                ActivityCache.getScreenManager().popActivity(activityContext);
//            }

            activityContext.finish();
        }
    }

    public static void exitApp(Context context) {
        SharedPreferences.Editor editor = context.getSharedPreferences("data", Context.MODE_PRIVATE).edit();
        editor.putBoolean("exitFlag", true).commit();

        Intent intent = new Intent(context, MainActivity.class);
        context.startActivity(intent);
    }

    /**
     * 判断用户是否同意打开相机权限
     * @return true 同意 false 拒绝
     */
    public static boolean isCameraPermission() {

        try {
            Camera.open().release();
            return true;
        } catch (Throwable e) {
            return false;
        }
    }

    public static boolean isNetworkConnected(Context context) {
        return Client.isNetworkConnect(context);
//        ConnectivityManager mConnectivityManager = (ConnectivityManager) activityContext
//                .getSystemService(Context.CONNECTIVITY_SERVICE);
//        NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
//        if (mNetworkInfo != null) {
//            go_back_white mNetworkInfo.isAvailable();
//        }
//        go_back_white false;
    }

    public static void startBlockDialog() {
        startBlockDialog("正在同步数据...");
    }

    public static void startBlockDialog(String showText) {

        if (loadingDialog == null
                || !loadingDialog.isShowing()) {
            // 显示
            loadingDialog = ZnkProgressDialog.createLoadingDialog(getContext(), showText);
            loadingDialog.show();
        }

    }

    public static void showTokenErrorDialog(String message, ZnkAlertDialog.OnClickCallBack callBack) {

        showTokenErrorDialog(getContext(), message, callBack);

    }

    public static synchronized void showTokenErrorDialog(Context context, String message, ZnkAlertDialog.OnClickCallBack callBack) {

        if (tokenErrorDialog == null
                || !tokenErrorDialog.isShowing()) {
            tokenErrorDialog = ZnkAlertDialog.createDialog(context, message, callBack);
            tokenErrorDialog.setCancelable(false);
            tokenErrorDialog.show();
        }

    }

    public static void overBlockDialog() {

        if (loadingDialog != null && loadingDialog.isShowing()) {
            loadingDialog.dismiss();
        }
    }

    public static Dialog getLoadingDialog(Context context, String showText) {
        return ZnkProgressDialog.createLoadingDialog(context, showText);
    }

    public static int dp2Px(float dp) {
        return (int) (dp * ZnkApplication.DENSITY + 0.5);
    }

    public static float px2Dp(int px) {
        return (float) (px / ZnkApplication.DENSITY + 0.5);
    }

    public static int getDisplayWidth(Context context) {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        return wm.getDefaultDisplay().getWidth();
    }

    public static int getDisplayHeight(Context context) {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        return wm.getDefaultDisplay().getHeight();
    }

    public static String getDeviceID() {
        TelephonyManager telephonyManager = (TelephonyManager) getContext().getSystemService(Context.TELEPHONY_SERVICE);
        return telephonyManager.getDeviceId();
    }

    @TargetApi(Build.VERSION_CODES.KITKAT)
    public static String getPath(final Uri uri) {

        if (uri == null) {
            return "";
        }

        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(activityContext, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }

                // TODO handle non-primary volumes
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {

                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                return getDataColumn(activityContext, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[] {
                        split[1]
                };

                return getDataColumn(activityContext, contentUri, selection, selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {

            // Return the remote address
            if (isGooglePhotosUri(uri))
                return uri.getLastPathSegment();

            return getDataColumn(activityContext, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        return null;
    }

    /**
     * Get the value of the data column for this Uri. This is useful for
     * MediaStore Uris, and other file-based ContentProviders.
     *
     * @param context The context.
     * @param uri The Uri to query.
     * @param selection (Optional) Filter used in the query.
     * @param selectionArgs (Optional) Selection arguments used in the query.
     * @return The value of the _data column, which is typically a file path.
     */
    public static String getDataColumn(Context context, Uri uri, String selection,
                                       String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {
                column
        };

        try {
            cursor = context.getContentResolver().query(
                    uri, projection, selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                final int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }


    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is Google Photos.
     */
    public static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }

    public static String getSubName(String strName, int maxLen) {

        if (strName == null
                || strName.getBytes().length <= maxLen) {
            return strName;
        }

        String strPrefix = "";
        String strSuffix = "";
        int length = 7;

        int count = 0;

        for (int i = 0; i < strName.length(); i++) {
            count += strName.substring(i, i + 1).getBytes().length;
            if (count >= length) {
                strPrefix = strName.substring(0, i + 1);
                break;
            }
        }

        count = 0;

        for (int i = strName.length() - 1; i >= 0; i--) {
            count += strName.substring(i, i + 1).getBytes().length;
            if (count >= length) {
                strSuffix = strName.substring(i, strName.length());
                break;
            }
        }

        return strPrefix + "..." + strSuffix;

    }
}
